<template>
  <div>
    <div class="checkAll" v-if="plainOptions.length>0">
      <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange"> 全选 </a-checkbox>
    </div>
    <div v-else style="text-align: center; padding: 10px 0 20px;">
      暂无数据
    </div>
    <a-checkbox-group v-model="checkedListData" :options="plainOptions" @change="onChange" >
      <span slot="label" slot-scope="option">{{ option }}</span>
    </a-checkbox-group>
  </div>
</template>
<script>
import { mapActions, mapState } from 'vuex'
import vueEvent from "@/utils/vueEvent";
export default {
  props: ['type','checkedList', 'plainOptions'],
  data() {
     return {
      checkAll: false,
      indeterminate: true,
      checkedListData: [],
      dataOptions: []
    };
  },
  watch: {
    // 获取已选的选项
    checkedList(val) {
      this.checkedListData = val//.map(Number)
    },
    // 监听选中的值传给父组件【防止初次打开编辑plainOptions过慢】
    plainOptions(val) {
      this.dataOptions = []
      this.dataOptions = this.filterData(val, this.checkedListData)
      this.checkedListData = this.dataOptions.map(v => v.value)
    },
    // 监听选中的值传给父组件
    checkedListData(val) {
      this.dataOptions = []
      this.dataOptions = this.filterData(this.plainOptions, val)

      let obj = {
        data: val, //选中的值
        dataOptions: this.dataOptions, //选中的数组对象
        type: this.type
      }

      this.$emit('setCheckedKeys', obj)
    },
  },
  methods: {
    onChange(data) {
      this.indeterminate = !!data.length && data.length < this.plainOptions.length;
      this.checkAll = data.length === this.plainOptions.length;
    },
    onCheckAllChange(e) {
      let val = this.plainOptions.map(v=>{return v.value})
      Object.assign(this, {
        checkedListData: e.target.checked ? val : [],
        indeterminate: false,
        checkAll: e.target.checked,
      });
    },
    // datas需筛选的数组集，checkedListData选中的数组值
    filterData(datas, checkedListData) {
      return datas.filter(item => checkedListData.indexOf(item.value) > -1)
    }
  },
};
</script>
<style lang="less" scoped>
.checkAll {
  border-bottom: 1px solid #e9e9e9;
  padding-bottom: 5px;
  padding-left: 4px;
}
</style>
